/*
 * @Author: your name
 * @Date: 2020-01-27 17:43:51
 * @LastEditTime: 2020-06-03 18:52:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-element-admin\src\utils\permission.js
 */
import store from '@/store'

/**
 * @param {Array} value
 * @returns {Boolean}
 * @example see @/views/permission/directive.vue
 */
export function checkPermission2(route) {
  let accessRoutes = []
  let routes = store.state.permission.routes.filter((r) => {
    return r.hidden == false
  })
  // console.log('routes+++++++++++', routes)
  generaResultRoutes(accessRoutes, '', routes, 1)
  // console.log('accessRoutes++++++++++', accessRoutes)
  let hasPermission = accessRoutes.includes(route)

  return hasPermission

}

function generaResultRoutes(accessRoutes, path, data, level) {
  data.forEach(item => {
    let rpath = path
    if (level == 1) {
      rpath = rpath + item.path
    } else {
      rpath = rpath + "/" + item.path
    }
    if (item.children && item.children.length > 0) {
      level++
      generaResultRoutes(accessRoutes, rpath, item.children, level)
    } else {
      level++
      accessRoutes.push(rpath)
    }
    level--
  })
}

export default function checkPermission(value) {
  if (value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles
    const permissionRoles = value

    const hasPermission = roles.some(role => {
      return permissionRoles.includes(role)
    })

    // console.log('888888888888888', hasPermission)

    if (!hasPermission) {
      return false
    }
    return true
  } else {
    console.error(`need roles! Like v-permission="['admin','editor']"`)
    return false
  }
}
